package com.boarsoft.boar.soagov.face.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.entity.FaceParam;
import com.boarsoft.boar.soagov.face.FaceParamBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("faceParamBiz")
public class FaceParamBizImpl extends SimpleBizImpl implements FaceParamBiz {
	@Override
	@Transactional(readOnly = true)
	public PagedResult<FaceParam> list(String faceId, short flag, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append("and faceId='").append(faceId).append("' and flag=").append(flag);
		int total = dao.getTotal(FaceParam.class, sb.toString());
		List<FaceParam> lt = dao.list(FaceParam.class, sb.toString(), pageNo, pageSize);
		return new PagedResult<FaceParam>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public ReplyInfo<Object> add(FaceParam o) {
		// 需保证参数名在接口中是唯一的
		StringBuilder sb = new StringBuilder();
		sb.append("and code='").append(o.getCode());
		sb.append("' and flag=").append(o.getFlag());
		sb.append(" and faceId='").append(o.getFaceId()).append("'");
		if (dao.find(FaceParam.class, sb.toString()) != null) {
			return new ReplyInfo<Object>(Constants.ERROR_DUPLICATED);
		}
		dao.save(o);
		return new ReplyInfo<Object>(true, o);
	}

	@Override
	@Transactional
	public ReplyInfo<Object> update(FaceParam o) {
		dao.update(o);
		return new ReplyInfo<Object>(true, o);
	}

	@Override
	@Transactional
	public void delete(String id) {
		dao.delete(FaceParam.class, id);
	}

	@Override
	@Transactional(readOnly = true)
	public FaceParam get(String id) {
		return (FaceParam) dao.get(FaceParam.class, id);
	}

	@Override
	@Transactional(readOnly = true)
	public List<FaceParam> listOutputOf(String faceIds) {
		StringBuilder sb = new StringBuilder();
		sb.append("and faceId in ('").append(faceIds).append("'");
		sb.append(") and flag = ").append(FaceParam.FLAG_OUTPUT);
		return dao.list(FaceParam.class, sb.toString());
	}

	@Override
	@Transactional
	public void copy(String sourceFaceId, String newFaceId) {
		List<FaceParam> lt = this.listOutputOf(sourceFaceId);
		for (FaceParam p : lt) {
			FaceParam f = (FaceParam) this.transfer(p, FaceParam.class);
			f.setId(null);
			f.setFaceId(newFaceId);
			dao.save(f);
		}
	}

	@Override
	@Transactional
	public ReplyInfo<Object> save(FaceParam c) {
		if (Util.strIsEmpty(c.getId())) {
			return this.add(c);
		}
		return this.update(c);
	}
}